<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use app\portal\model\PortalTagModel;
use app\portal\model\PortalPostModel;

class TagController extends HomeBaseController
{
    /**
     * 标签
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $id             = $this->request->param('id');
        $page             = $this->request->param('page',1);
        $pageSize = 15;

        $portalTagModel = new PortalTagModel();
        $PortalPostModel = new PortalPostModel();

        if(is_numeric($id)){
            $tag = $portalTagModel->where('id', $id)->where('status', 1)->find();
        }else{
            $tag = $portalTagModel->where('name', $id)->where('status', 1)->find();
        }


        if (empty($tag)) {
            abort(404, '标签不存在!');
        }

        //相关文章
        $data =   $portalTagModel->tagArticleLists($tag['id']);
        $pages = $data->render();
        $data =json_decode(json_encode($data),true);
        $total = $data['total'];

        $routeData = $PortalPostModel->getRouteData();
        $result = $PortalPostModel->getRealUrlLists($data['data'],$routeData);

        $tagLists = $portalTagModel->articleTagLists(array_column($result,'id'));
        foreach($result as $k=>&$v){
            $v['taglist'] = isset($tagLists[$v['id']]) ? $tagLists[$v['id']] : [];
        }

        //最新(随机)文章
       // $newData =  $PortalPostModel-> randomLists(10);
        $site_name = config('selfconfig.site_name');
        $site_type = config('selfconfig.site_type');
        $tag["desc"] = sprintf("%s,%s基于%s行业的%s知识大纲,提供丰富的%s知识大全, 并涵盖所有%s百科知识。",$site_name,$tag['name'],$site_type,$site_type,$site_type,$site_type);


        $this->assign('tag', $tag);
        $this->assign('relateData', $result);
       // $this->assign('data', $newData);
        $this->assign('pages', $pages);
        $this->assign('total', $total);

        return $this->fetch('/tag');
    }

}
